#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    connect(ui->pushButtonToHex, SIGNAL(clicked()), this, SLOT(toHex()));
    connect(ui->pushButtonFromHex, SIGNAL(clicked()), this, SLOT(fromHex()));
}

Dialog::~Dialog()
{
    delete ui;
}

char hexDigitAt(const QByteArray& arr, int ii)
{
    unsigned char hexDigit = arr[ii / 2];
    if (ii % 2)
        hexDigit &= 0xf;
    else
        hexDigit >>= 4;
    static const char* hexDigitAsChar = "0123456789ABCDEF";
    return hexDigitAsChar[hexDigit];
}

void Dialog::toHex()
{
    QString format = ui->lineEditFormat->text();
    format.replace("\\n", "\n");

    int hexDigitCount = 0;
    for (int ii = 1; ii < 100; ii++)
        if (-1 != format.indexOf(QString("%%1").arg(ii)))
            hexDigitCount++;

    QByteArray data = ui->plainTextEditAscii->toPlainText().toUtf8();
    QString hex;
    QString formattedHex = format;
    for (int ii=0; ii<data.size() * 2; ii++)
    {
        formattedHex = formattedHex.arg(hexDigitAt(data, ii));

        if (0 == ((ii + 1) % hexDigitCount))
        {
            hex += formattedHex;
            formattedHex = format;
        }
    }

    ui->plainTextEditHex->setPlainText(hex);
}

void Dialog::fromHex()
{
    QString hex = ui->plainTextEditHex->toPlainText().remove(QRegExp(ui->lineEditRemove->text())).toUpper();
    QByteArray utf8;
    utf8.resize(hex.size() / 2);

    for (int ii = 0; ii < utf8.size(); ii++)
    {
        char ch, hexDigit1, hexDigit2;

        // get first digit (in 0xCD that would be C)
        ch = hex[2*ii].toAscii();
        if (ch >= '0' && ch <= '9')
            hexDigit1 = ch - '0';
        else
            hexDigit1 = ch - 'A' + 10;

        // get second digit (in 0xCD that would be D)
        ch = hex[2*ii + 1].toAscii();
        if (ch >= '0' && ch <= '9')
            hexDigit2 = ch - '0';
        else
            hexDigit2 = ch - 'A' + 10;

        utf8[ii] = 16 * hexDigit1 + hexDigit2;
    }

    ui->plainTextEditAscii->setPlainText(QString::fromUtf8(utf8));
}
